package com.xiaoluo.lottery.web;

import com.xiaoluo.lottery.exception.LotteryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Caedmon on 2016/4/6.
 */
public class BaseController {
    private static final Logger log= LoggerFactory.getLogger(BaseController.class);
    @InitBinder
    public void init(HttpServletRequest request, ServletRequestDataBinder binder) throws UnsupportedEncodingException {

        request.setCharacterEncoding("UTF-8");
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CustomDateEditor editor=new CustomDateEditor(format,true);
        binder.registerCustomEditor(Date.class, editor);

    }
    @ExceptionHandler
    public @ResponseBody
    String handleException(HttpServletRequest request,Throwable ex){
        ApiResult result=new ApiResult();

         if(ex instanceof LotteryException){
             LotteryException se=(LotteryException)ex;
             result.setCode(10002);
            result.setMsg(se.getError());
        }else{
            ex.printStackTrace();
            log.error("Api system error {}",request.getRequestURL(),ex);
            result.setCode(10001);
            result.setMsg("请求处理异常:"+ex.getMessage());
        }
        return result.toString();
    }

}
